# Create your views here.
from django.template.loader import get_template
from django.template import Context,RequestContext

from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.conf import settings

import traceback,sys

#Ajax new implementation
from django.utils import simplejson
import MySQLdb

import datetime

def get_status_ibov(template_name='menu_dir_temp_about_orange.html'):
    try:        
        db = MySQLdb.connect(user = settings.STOCKS_DB_USER, 
                            db = settings.STOCKS_DB_NAME, 
                            passwd = settings.STOCKS_DB_PASS, 
                            host = settings.STOCKS_DB_HOST, 
                            port = settings.STOCKS_DB_PORT)
               
        #PROD
        #'''
        query_select = """
                        SELECT `id_ibov`, `data`, `hora`, `fechamento`, `variacao`, `max`, `min`, `ultima`, `volume`, `abertura`, `porc`, 
                        DATE_FORMAT(data_hora_real,'%H:%i:%S') 
                        FROM `stocks_db`.`ibov_status` ORDER BY `id_ibov` DESC LIMIT 1;
                        """  
        #'''
        #print "query_select: %s" % (query_select)
        cursor = db.cursor()
        cursor.execute(query_select)
        response_dict = {}
        
        #status pregao
        now = datetime.datetime.now()
        if (8 < now.hour < 15):
            response_dict['response_status_ibov_pregao'] = 'Aberto'
        elif (15 < now.hour < 17):
            response_dict['response_status_ibov_pregao'] = 'After'
        else:
            response_dict['response_status_ibov_pregao'] = 'Fechado'
            
        response_dict['response_status_ibov'] = cursor.fetchall()
        print response_dict['response_status_ibov']
        response_dict['fields_status_ibov'] = cursor.description
        response_dict['template_name'] = template_name
        db.close()
        
        if len(response_dict['response_status_ibov'])>0:
            return response_dict
        else:
            return None
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout) 

def get_status_ibov_ajax_html(request):
    try:
        response_dict=get_status_ibov()
        if response_dict:
            t = get_template(response_dict['template_name'])
            c = RequestContext(request,response_dict)
            html = t.render(c)
            return HttpResponse(html, mimetype='text/html; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout)

def get_status_ibov_ajax_json(request):
    try:
        #print "ultimo_time:%s" % (ultimo_time)        
        response_dict=get_status_ibov()
        if response_dict:
            return HttpResponse(simplejson.dumps(response_dict['response_status_ibov']), mimetype='application/json; charset=UTF-8')
        else:
            return HttpResponse(simplejson.dumps('UN'), mimetype='application/json; charset=UTF-8')
    except:
        exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()
        traceback.print_exception(exceptionType, exceptionValue, exceptionTraceback,
                          limit=2, file=sys.stdout) 